package com.wyzz.hr.action;

import java.io.File;
import java.io.FileInputStream;
import java.math.BigDecimal;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.lang.StringUtils;
import org.hibernate.criterion.DetachedCriteria;

import com.wyzz.hr.base.Constants;
import com.wyzz.hr.base.FileOperate;
import com.wyzz.hr.base.Status;
import com.wyzz.hr.bo.ICompaplanBo;
import com.wyzz.hr.bo.IEmployeeBo;
import com.wyzz.hr.bo.ISalaryPaidBo;
import com.wyzz.hr.bo.ISalaryconfBo;
import com.wyzz.hr.exportfile.ExportSalaryConfig;
import com.wyzz.hr.pojo.Employee;
import com.wyzz.hr.pojo.Empsalaryacctversion;
import com.wyzz.hr.pojo.Empsalaryconfig;
import com.wyzz.hr.pojo.Emptype;
import com.wyzz.hr.pojo.Jobgrade;
import com.wyzz.hr.pojo.Location;
import com.wyzz.hr.spring.SpringBeanFactory;
import com.wyzz.hr.util.BaseCrit;
import com.wyzz.hr.util.Pager;
import com.wyzz.hr.util.impl.PropertiesFileConfigManager;

public class SalaryConfigAction extends CompAction implements Status, Constants {

	public SalaryConfigAction() {
		searchOrExport = null;
		docStream = null;
		contentDisposition = null;
		serverFileName = null;
		page = new Pager();
		emp = new Employee();
		emp.setEmpStatus(Integer.valueOf(1));
	}

	public String execute() throws Exception {
		DetachedCriteria dc = DetachedCriteria
				.forClass(Employee.class);
		if ("SUB".equals(super.authorityCondition)) {
			addSubDC(dc, "", 2);
			if (emp.getEmpStatus() == null)
				emp.setEmpStatus(Integer.valueOf(1));
		}
		addCriteria(dc);
		IEmployeeBo empBo = (IEmployeeBo) getBean("empBo");
		setEmpStatus(empBo.getEmpStatus());
		getDrillDownList();
		ISalaryconfBo salaryConfBo = (ISalaryconfBo) getBean("salaryconfBo");
		if ("export".equals(searchOrExport)
				&& super.authorityCondition.equalsIgnoreCase("HR")) {
			Map map = salaryConfBo.findSalaryConfigByNoPage(dc, page,
					emp);
			if (map == null) {
				addActionError("\u672C\u6B21\u67E5\u8BE2\u6CA1\u6709\u6570\u636E\u53EF\u4EE5\u5BFC\u51FA\uFF01");
				return "success";
			}
			try {
				String filePath = FileOperate.getFileHomePath();
				String xslFileName = (new StringBuilder())
						.append("export-")
						.append(FileOperate.buildFileName())
						.append(
								PropertiesFileConfigManager.getInstance()
										.getProperty("sys.saveDir.type").trim())
						.toString();
				filePath = (new StringBuilder()).append(filePath).append(
						xslFileName).toString();
				ExportSalaryConfig exportSalaryConfig = new ExportSalaryConfig(
						map);
				exportSalaryConfig.export(filePath);
				File file = new File(filePath);
				FileInputStream fileInputStream = new FileInputStream(file);
				setDocStream(fileInputStream);
				String downFileName = "salaryConfig.xls";
				setContentDisposition((new StringBuilder()).append(
						"filename=\"").append(downFileName).append("\"")
						.toString());
				setServerFileName(filePath);
				clearErrorsAndMessages();
				return "download";
			} catch (Exception e) {
				addActionError("\u6570\u636E\u5BFC\u51FA\u5931\u8D25\uFF01");
				e.printStackTrace();
				return "success";
			}
		}
		addOrders(dc, page, new String[] {
				(new StringBuilder()).append("config.").append(
						Empsalaryconfig.PROP_ESC_LAST_CHANGE_TIME).append(
						"-down").toString(),
				(new StringBuilder()).append(Employee.PROP_EMP_DISTINCT_NO)
						.append("-up").toString() });
		setEmployeeList(salaryConfBo.findSalaryConfig(dc, page, emp));
		if (!StringUtils.isEmpty(actionErrorS)) {
			addDwrInfo(actionErrorS);
			actionErrorS = null;
		}
		return "success";
	}

	private void addCriteria(DetachedCriteria dc) {
		BaseCrit.addEmpDC(dc, null, emp.getEmpName());
		BaseCrit.addDeptDC(dc, Employee.PROP_EMP_DEPT_NO,
				Employee.PROP_EMP_PB_NO, null, emp.getEmpDeptNo());
		BaseCrit.addDC(dc, Employee.PROP_EMP_TYPE, Emptype.PROP_ID,
				new Object[] { emp.getEmpType() });
		BaseCrit.addDC(dc, Employee.PROP_EMP_LOCATION_NO, Location.PROP_ID,
				new Object[] { emp.getEmpLocationNo() });
		BaseCrit.addDC(dc, Employee.PROP_EMP_STATUS, "eq", new Integer[] { emp
				.getEmpStatus() });
		if (emp.getConfig() != null) {
			BaseCrit.addDC(dc, (new StringBuilder()).append("config.").append(
					Empsalaryconfig.PROP_ESC_JOBGRADE).toString(),
					Jobgrade.PROP_ID, new Object[] { emp.getConfig()
							.getEscJobgrade() });
			BaseCrit.addDC(dc, (new StringBuilder()).append("config.").append(
					Empsalaryconfig.PROP_ESC_ESAV_ID).toString(),
					Empsalaryacctversion.PROP_ID, new Object[] { emp
							.getConfig().getEscEsavId() });
			BaseCrit.addDC(dc, (new StringBuilder()).append("config.").append(
					Empsalaryconfig.PROP_ESC_COST_CENTER).toString(), "eq",
					new String[] { emp.getConfig().getEscCostCenter() });
		}
	}

	private void getDrillDownList() {
		departs = getDrillDown("Department", new String[0]);
		location = getDrillDown("Location", new String[0]);
		emptype = getDrillDown("EmpType", new String[0]);
		jobgradeList = getDrillDown("Jobgrade", new String[0]);
		acctList = getDrillDown("EmpSalaryAcct", new String[0]);
		costCenterList = getDrillDown("CostCenter", new String[0]);
	}

	public String updateSalaryConfig() {
		if (StringUtils.isEmpty(id) || empsalaryconfig.getEscJobgrade() == null
				|| empsalaryconfig.getEscEsavId() == null) {
			addErrorInfo(msgParamEx, new Object[] { "paramex" });
			return "input";
		}
		if (StringUtils.isEmpty(empsalaryconfig.getEscBankAccountNo())) {
			addErrorInfo(msgNullErr,
					new Object[] { "\u5458\u5DE5\u94F6\u884C\u8D26\u53F7" });
			return "input";
		}
		IEmployeeBo empBo = (IEmployeeBo) getBean("empBo");
		Employee employee = empBo.loadEmp(id, new String[] { "config" });
		Empsalaryconfig config = employee.getConfig();
		if (config == null) {
			addErrorInfo(msgNoConfig, new Object[] { "noconf",
					employee.getEmpName() });
			return "input";
		}
		config.setEscJobgrade(empsalaryconfig.getEscJobgrade());
		config.setEscEsavId(empsalaryconfig.getEscEsavId());
		config
				.setEscBankAccountNo(empsalaryconfig.getEscBankAccountNo()
						.trim());
		if (!StringUtils.isEmpty(empsalaryconfig.getEscBankName()))
			config.setEscBankName(empsalaryconfig.getEscBankName().trim());
		if (!StringUtils.isEmpty(empsalaryconfig.getEscCostCenter()))
			config.setEscCostCenter(empsalaryconfig.getEscCostCenter().trim());
		try {
			for (int i = 0; i < 48; i++) {
				Object escValue = PropertyUtils.getProperty(empsalaryconfig,
						(new StringBuilder()).append("escColumn").append(i + 1)
								.toString());
				if (escValue != null)
					PropertyUtils.setProperty(config, (new StringBuilder())
							.append("escColumn").append(i + 1).toString(),
							((BigDecimal) escValue).setScale(2));
			}

		} catch (Exception e) {
			e.printStackTrace();
			addErrorInfo(msgSystemEx);
			return "input";
		}
		ISalaryconfBo salaryconfBo = (ISalaryconfBo) getBean("salaryconfBo");
		if (salaryconfBo.updateSalaryconf(config, getCurrentEmpNo())) {
			addSuccessInfo(msgUpdConfSucc, new Object[] { "SUCC",
					employee.getEmpName() });
			return "success";
		} else {
			addErrorInfo(msgUpdConfFail, new Object[] { "fail",
					employee.getEmpName() });
			return "input";
		}
	}

	public String addSalaryConfig() {
		System.out.println("ggeeeeeeeeeeeg");
		if (StringUtils.isEmpty(id) || empsalaryconfig.getEscJobgrade() == null
				|| empsalaryconfig.getEscEsavId() == null) {
			addErrorInfo(msgParamEx, new Object[] { "paramex" });
			return "success";
		}
		if (StringUtils.isEmpty(empsalaryconfig.getEscBankAccountNo())) {
			addErrorInfo(msgNullErr,
					new Object[] { "\u5458\u5DE5\u94F6\u884C\u8D26\u53F7" });//员工银行账号
			return "success";
		}
		IEmployeeBo empBo = (IEmployeeBo) getBean("empBo");
		Employee employee = empBo.loadEmp(id, new String[] { "config" });
		if (employee == null) {
			addErrorInfo(msgNoEmp, new Object[] { "noemp" });
			return "success";
		}
		if (employee.getConfig() != null) {
			addErrorInfo(msgHasConfig, new Object[] { "hasconf",
					employee.getEmpName() });
			return "success";
		}
		empsalaryconfig.setId(id);
		empsalaryconfig.setEmployee(employee);
		empsalaryconfig.setEscBankAccountNo(empsalaryconfig
				.getEscBankAccountNo().trim());
		if (!StringUtils.isEmpty(empsalaryconfig.getEscBankName()))
			empsalaryconfig.setEscBankName(empsalaryconfig.getEscBankName()
					.trim());
		if (!StringUtils.isEmpty(empsalaryconfig.getEscCostCenter()))
			empsalaryconfig.setEscCostCenter(empsalaryconfig.getEscCostCenter()
					.trim());
		ISalaryconfBo salaryBo = (ISalaryconfBo) getBean("salaryconfBo");
		if (salaryBo.insertSalaryconf(empsalaryconfig, getCurrentEmpNo(),
				employee)) {
			addSuccessInfo(msgCreateConfSucc, new Object[] { "SUCC",
					employee.getEmpName() });
			return "success";
		} else {
			addErrorInfo(msgCreateConfFail, new Object[] { "fail",
					employee.getEmpName() });
			return "success";
		}
	}

	public String getJobgradeName(String id) {
		for (Iterator i$ = jobgradeList.iterator(); i$.hasNext();) {
			Jobgrade jobgrade = (Jobgrade) i$.next();
			if (jobgrade.getId().equalsIgnoreCase(id))
				return jobgrade.getJobGradeName();
		}

		return "";
	}

	public String addSalaryConfigInit() throws Exception {
		if (StringUtils.isEmpty(id)) {
			addErrorInfo(msgParamEx, new Object[] { "paramex" });
			return "error";
		}
		IEmployeeBo empBo = (IEmployeeBo) getBean("empBo");
		employee = empBo.loadEmp(id, new String[] { "empType", "config" });
		if (employee == null) {
			addErrorInfo(msgNoEmp, new Object[] { "noemp" });
			return "error";
		}
		if (employee.getConfig() != null) {
			addErrorInfo(msgHasConfig, new Object[] { "hasconf",
					employee.getEmpName() });
			return "error";
		} else {
			jobgradeList = getDrillDown("Jobgrade", new String[0]);
			acctList = getDrillDown("EmpSalaryAcct", new String[0]);
			return "success";
		}
	}

	public String updateSalaryConfigInit() throws Exception {
		if (StringUtils.isEmpty(id)) {
			addErrorInfo(msgParamEx, new Object[] { "paramex" });
			return "error";
		}
		IEmployeeBo empBo = (IEmployeeBo) getBean("empBo");
		employee = empBo.loadEmp(id, new String[] { Employee.PROP_EMP_TYPE,
				Employee.PROP_EMP_PB_NO });
		if (employee == null) {
			addErrorInfo(msgNoEmp, new Object[] { "noemp" });
			return "error";
		}
		ISalaryconfBo salaryBo = (ISalaryconfBo) getBean("salaryconfBo");
		empsalaryconfig = salaryBo.loadSalaryconf(id, new String[] {
				"escEsavId", "escJobgrade", "escEsavId.esavEsac" });
		if (empsalaryconfig == null) {
			addErrorInfo(msgNoConfig, new Object[] { "noconf",
					employee.getEmpName() });
			return "error";
		} else {
			empsalaryconfig.decryEmpSalaryConf(empsalaryconfig);
			jobgradeList = getDrillDown("Jobgrade", new String[0]);
			acctList = getDrillDown("EmpSalaryAcct", new String[0]);
			return "success";
		}
	}

	public String deleteSalaryConfig() {
		if (StringUtils.isEmpty(id)) {
			addErrorInfo(msgParamEx, new Object[] { "paramex" });
			return "error";
		}
		IEmployeeBo empBo = (IEmployeeBo) getBean("empBo");
		Employee employeeFromDB = empBo.loadEmp(id, new String[] { "config" });
		if (employeeFromDB == null) {
			addErrorInfo(msgNoEmp, new Object[] { "noemp" });
			return "error";
		}
		if (employeeFromDB.getConfig() == null) {
			addErrorInfo(msgNoConfig, new Object[] { "noconf",
					employeeFromDB.getEmpName() });
			return "error";
		}
		String errorMsg = "";
		ISalaryPaidBo salaryPaidBo = (ISalaryPaidBo) getBean("salaryPaidBo");
		if (salaryPaidBo.isSalaryPayRecordsExist(id))
			errorMsg = (new StringBuilder()).append(errorMsg).append(
					"\u5B58\u5728\u85AA\u8D44\u53D1\u653E\u8BB0\u5F55\uFF0C")
					.toString();
		ICompaplanBo compaplanBo = (ICompaplanBo) getBean("compaplanBo");
		if (compaplanBo.loadCompaplanInfoByEmpNo(id) != null)
			errorMsg = (new StringBuilder()).append(errorMsg).append(
					"\u5B58\u5728\u8C03\u85AA\u8BA1\u5212\uFF0C").toString();
		if (!StringUtils.isEmpty(errorMsg)) {
			addErrorInfo(msgDelConfFail, new Object[] { "fail", errorMsg,
					employeeFromDB.getEmpName() });
			return "error";
		}
		ISalaryconfBo salaryconfigBO = (ISalaryconfBo) SpringBeanFactory
				.getBean("salaryconfBo");
		if (salaryconfigBO.deleteSalaryconf(id, getCurrentEmp())) {
			addSuccessInfo(msgDelConfSucc, new Object[] { "SUCC",
					employeeFromDB.getEmpName() });
			return "success";
		} else {
			addErrorInfo(msgDelConfFail, new Object[] { "fail", "",
					employeeFromDB.getEmpName() });
			return "success";
		}
	}

	public Pager getPage() {
		return page;
	}

	public void setPage(Pager page) {
		this.page = page;
	}

	public List getEmpStatus() {
		return empStatus;
	}

	public void setEmpStatus(List empStatus) {
		this.empStatus = empStatus;
	}

	public List getEmployeeList() {
		return employeeList;
	}

	public void setEmployeeList(List employeeList) {
		this.employeeList = employeeList;
	}

	public List getDeparts() {
		return departs;
	}

	public void setDeparts(List departs) {
		this.departs = departs;
	}

	public List getEmptype() {
		return emptype;
	}

	public void setEmptype(List emptype) {
		this.emptype = emptype;
	}

	public List getLocation() {
		return location;
	}

	public void setLocation(List location) {
		this.location = location;
	}

	public void setAcctList(List acctList) {
		this.acctList = acctList;
	}

	public Employee getEmp() {
		return emp;
	}

	public void setEmp(Employee emp) {
		this.emp = emp;
	}

	public String getContentDisposition() {
		return contentDisposition;
	}

	public void setContentDisposition(String contentDisposition) {
		this.contentDisposition = contentDisposition;
	}

	public FileInputStream getDocStream() {
		return docStream;
	}

	public void setDocStream(FileInputStream docStream) {
		this.docStream = docStream;
	}

	public String getSearchOrExport() {
		return searchOrExport;
	}

	public void setSearchOrExport(String searchOrExport) {
		this.searchOrExport = searchOrExport;
	}

	public String getEmployeeForQuery() {
		return employeeForQuery;
	}

	public void setEmployeeForQuery(String employeeForQuery) {
		this.employeeForQuery = employeeForQuery;
	}

	public List getJobgradeList() {
		return jobgradeList;
	}

	public void setJobgradeList(List jobgradeList) {
		this.jobgradeList = jobgradeList;
	}

	public List getAcctList() {
		return acctList;
	}

	public String getServerFileName() {
		return serverFileName;
	}

	public void setServerFileName(String serverFileName) {
		this.serverFileName = serverFileName;
	}

	public Empsalaryconfig getEmpsalaryconfig() {
		return empsalaryconfig;
	}

	public void setEmpsalaryconfig(Empsalaryconfig empsalaryconfig) {
		this.empsalaryconfig = empsalaryconfig;
	}

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public Employee getEmployee() {
		return employee;
	}

	public void setEmployee(Employee employee) {
		this.employee = employee;
	}

	public String getDefaultAcct() {
		return defaultAcct;
	}

	public void setDefaultAcct(String defaultAcct) {
		this.defaultAcct = defaultAcct;
	}

	public List getCostCenterList() {
		return costCenterList;
	}

	public void setCostCenterList(List costCenterList) {
		this.costCenterList = costCenterList;
	}

	public String getActionErrorS() {
		return actionErrorS;
	}

	public void setActionErrorS(String actionErrorS) {
		this.actionErrorS = actionErrorS;
	}

	private static final long serialVersionUID = 0xc53a77b0ae03eebfL;
	private String searchOrExport;
	private FileInputStream docStream;
	private String contentDisposition;
	private String serverFileName;
	private Employee emp;
	private List jobgradeList;
	private List acctList;
	private List employeeList;
	private List empStatus;
	private List departs;
	private List emptype;
	private List location;
	private List costCenterList;
	private String employeeForQuery;
	private Empsalaryconfig empsalaryconfig;
	private String id;
	private Employee employee;
	private String defaultAcct;
	private Pager page;
	private String actionErrorS;
}
